package com.example.hybridmobiledemo.module.main.fragment.news;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.hybridmobiledemo.databinding.FragmentScienceBinding;
import com.example.hybridmobiledemo.module.main.bean.NewsInfo;
import com.example.hybridmobiledemo.module.main.bean.SCNewsAllInfo;
import com.example.hybridmobiledemo.util.OkHttpUtils;
import com.example.hybridmobiledemo.view.NewsRvAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EntertainmentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EntertainmentFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "id";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private FragmentScienceBinding binding;
    private RefreshLayout refreshLayout;
    private RecyclerView rvNewsScience;
    private Thread thread;
    private String id;
    private List<NewsInfo> newsInfoList = new ArrayList<NewsInfo>();
    private int newsCount;

    public EntertainmentFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment EntertainmentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EntertainmentFragment newInstance(String param1, String param2, String id) {
        EntertainmentFragment fragment = new EntertainmentFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            id = getArguments().getString(ARG_PARAM3);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentScienceBinding.inflate(inflater, container, false);
        initView();
        initData();
        // Inflate the layout for this fragment
        return binding.getRoot();
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url("interface/SCNews/getAll")
                        .addParam("userId", "ODky")
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                try {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Gson gson = new Gson();
                                            SCNewsAllInfo info = gson.fromJson(json, SCNewsAllInfo.class);
                                            List<SCNewsAllInfo.DataBean> list = info.getData();
                                            int count = 0;
                                            for (int i = 0; i < list.size(); i++) {
                                                String scNewsTypeId = String.valueOf(list.get(i).getsCNewsTypeId());
                                                if (scNewsTypeId.equals(id)) {
                                                    int newsId = list.get(i).getId();
                                                    String name = list.get(i).getName();
                                                    String content = list.get(i).getContent();
                                                    int createTime = list.get(i).getCreateTime();
                                                    String author = list.get(i).getAuthor();
                                                    newsInfoList.add(new NewsInfo(newsId, scNewsTypeId,
                                                            name, content, createTime, author));
                                                    count++;
                                                    if (count == 10) {
                                                        newsCount = i;
                                                        break;
                                                    }
                                                }
                                            }
                                            rvNewsScience.setLayoutManager(new LinearLayoutManager(getContext()));
                                            rvNewsScience.setAdapter(new NewsRvAdapter(newsInfoList, getContext()));
                                            //下拉刷新
                                            refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
                                            //上拉加载
                                            refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
                                            //为下拉刷新添加事件
                                            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                                                @Override
                                                public void onRefresh(RefreshLayout refreshlayout) {
                                                    Log.i("TAG", "下拉刷新");
                                                    newsInfoList.clear();
                                                    int mCount = 0;
                                                    for (int i = 0; i < list.size(); i++) {
                                                        String scNewsTypeId = String.valueOf(list.get(i).getsCNewsTypeId());
                                                        if (scNewsTypeId.equals(id)) {
                                                            int newsId = list.get(i).getId();
                                                            String name = list.get(i).getName();
                                                            String content = list.get(i).getContent();
                                                            int createTime = list.get(i).getCreateTime();
                                                            String author = list.get(i).getAuthor();
                                                            newsInfoList.add(new NewsInfo(newsId, scNewsTypeId,
                                                                    name, content, createTime, author));
                                                            mCount++;
                                                        }
                                                        if (mCount == 10) {
                                                            newsCount = i;
                                                            break;
                                                        }
                                                    }
                                                    rvNewsScience.setLayoutManager(new LinearLayoutManager(getContext()));
                                                    rvNewsScience.setAdapter(new NewsRvAdapter(newsInfoList, getContext()));
                                                    refreshlayout.finishRefresh(true);//传入false表示刷新失败
                                                }
                                            });
                                            //为上拉下载添加事件
                                            refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
                                                @Override
                                                public void onLoadmore(RefreshLayout refreshlayout) {
                                                    Log.i("TAG", "上拉下载");
                                                    int iCount = 0;
                                                    for (int i = newsCount; i < list.size(); i++) {
                                                        String scNewsTypeId = String.valueOf(list.get(i).getsCNewsTypeId());
                                                        if (scNewsTypeId.equals(id)) {
                                                            int newsId = list.get(i).getId();
                                                            String name = list.get(i).getName();
                                                            String content = list.get(i).getContent();
                                                            int createTime = list.get(i).getCreateTime();
                                                            String author = list.get(i).getAuthor();
                                                            newsInfoList.add(new NewsInfo(newsId, scNewsTypeId,
                                                                    name, content, createTime, author));
                                                            iCount++;
                                                        }
                                                        if (iCount == 10) {
                                                            newsCount = i;
                                                            break;
                                                        }
                                                    }
                                                    rvNewsScience.setLayoutManager(new LinearLayoutManager(getContext()));
                                                    rvNewsScience.setAdapter(new NewsRvAdapter(newsInfoList, getContext()));
                                                    refreshlayout.finishLoadmore(2000);//传入false表示加载失败
                                                }
                                            });
                                        }
                                    });
                                } catch (Exception e) {
                                    Log.e("TAG", "runOnUiThread");
                                }
                            }

                            @Override
                            public void onFailure(Exception e) {

                            }
                        });
            }
        }).start();
    }

    private void initView() {
        refreshLayout = binding.refreshLayout;
        rvNewsScience = binding.rvNewsScience;
    }
}